package com.yq.core.dao.impl;

import com.yq.core.dao.UserDao;
import com.yq.core.dto.UserDO;
import com.yq.core.dto.UserDO_;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by yq on 16-5-25.
 */
@Stateless(name = "userDao")
public class UserDaoImpl implements UserDao {
    @PersistenceContext(unitName = "mallJPAUnit")
    private EntityManager entityManager;

    private static final Log log = LogFactory.getLog(UserDaoImpl.class);

    public List<UserDO> getUserList(UserDO userDO) {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<UserDO> criteriaQuery = criteriaBuilder.createQuery(UserDO.class);
        Root<UserDO> root = criteriaQuery.from(UserDO.class);
        List<Predicate> predicates = new ArrayList<Predicate>();
        Predicate condition = criteriaBuilder.equal(root.get(UserDO_.userId), userDO.getUserId());
        predicates.add(condition);
        criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()]));
        TypedQuery<UserDO> typedQuery = entityManager.createQuery(criteriaQuery);
        return typedQuery.getResultList();
    }

    public UserDO getUser(UserDO userDO) {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<UserDO> criteriaQuery = criteriaBuilder.createQuery(UserDO.class);
        Root<UserDO> root = criteriaQuery.from(UserDO.class);
        Predicate condition = criteriaBuilder.equal(root.get(UserDO_.username), userDO.getUsername());
        criteriaQuery.where(condition);
        TypedQuery<UserDO> typedQuery = entityManager.createQuery(criteriaQuery);
        return typedQuery.getSingleResult();
    }

    public void testSelectUserList(){
        UserDO userQueryDO = new UserDO();
        List<UserDO> userList = getUserList(userQueryDO);
        for (UserDO userDO : userList) {
            log.info("username is " + userDO.getUsername() + " password is " + userDO.getPassword());
        }
    }
}
